package com.century.sjt.util;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.century.sjt.R;
import com.century.sjt.photoview.PhotoViewAttacher;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * Created by pig33 on 15-08-27.
 */
public class FileUtil {

    //保存文件
    public static void saveImg(Bitmap bitmap,String imgId) {                            //保存用户头像到指定文件夹
        if (!imgId.equals("")) {
            File file = new File(Constant.CAMERA_PICTURE_PATH, imgId);
            if (file.exists()) {
                file.delete();
            }
            try {
                FileOutputStream out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //下载图片保存本地
    public static void savedownLoadImg(Bitmap bitmap, String imgId, Activity activity) {                            //保存用户头像到指定文件夹
        if (!imgId.equals("")) {
            File file = new File(Constant.DOWNLOAD_PICTURE_PATH, imgId+".jpg");
            if (file.exists()) {
                file.delete();
            }
            try {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+ Constant.DOWNLOAD_PICTURE_PATH+imgId+".jpg")));//扫描当前图片
        }
    }

    //判断文件是否存在
    public static boolean isFileExist(String fileName){
        boolean exist=false;
        if(!fileName.equals("")){
            File file=new File(fileName);
            if(file.exists()){
                exist=true;
            }
        }
        return exist;
    }

    //删除图片
    public static void deleteImageFile(String fileName) {
        try {
            File file = new File(fileName);
            file.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //创建文件目录
    public static void createImageDir(){
        File file=new File(Constant.SYSTEM_CACHE_PATH);
        if(!file.exists())file.mkdir();
        File file1=new File(Constant.CAMERA_PICTURE_PATH);
        if(!file1.exists())file1.mkdir();
        File file2=new File(Constant.DOWNLOAD_PICTURE_PATH);
        if(!file2.exists())file2.mkdir();
    }

    //下载图片
    public static void downLoadBigImage(final String picId,RequestQueue mQueue){
        File file = new File(Constant.CAMERA_PICTURE_PATH, picId);
        if(file.exists())return;
        ImageRequest imageRequest = new ImageRequest(Constant.URL_DOWNLOAD_IMG + picId + "&type=big", new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap bitmap) {
                FileUtil.saveImg(bitmap, picId);                //保存图片
            }
        }, 0, 0, ImageView.ScaleType.CENTER_CROP, Bitmap.Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        mQueue.add(imageRequest);
    }

    //下载图片并设置图片
    public static void setupBigImage(final String picId, RequestQueue mQueue, final ImageView imageView){
        createImageDir();
        File file = new File(Constant.CAMERA_PICTURE_PATH, picId);
        if(!file.exists()) {//文件不存在，下载下来
            ImageRequest imageRequest = new ImageRequest(Constant.ImageHost_Big+picId, new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap bitmap) {
                    imageView.setImageBitmap(bitmap);
                    FileUtil.saveImg(bitmap, picId);                //保存图片
                }
            }, 0, 0, ImageView.ScaleType.CENTER_CROP, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
//                    imageView.setBackgroundResource(R.mipmap.friend2x);
                }
            });
            mQueue.add(imageRequest);
        }else{
            Bitmap bitmap = BitmapFactory.decodeFile(Constant.CAMERA_PICTURE_PATH + picId);
            imageView.setImageBitmap(bitmap);
        }
    }
    //下载图片并设置图片showimage
    public static void setupBigImage(final String picId, RequestQueue mQueue, final ImageView imageView, final PhotoViewAttacher mAttacher, final ProgressDialog progressDialog, final Context context){
        createImageDir();
        File file = new File(Constant.CAMERA_PICTURE_PATH, picId);
        if(!file.exists()) {//文件不存在，下载下来
            ImageRequest imageRequest = new ImageRequest(Constant.ImageHost_Big+picId, new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap bitmap) {
                    imageView.setImageBitmap(bitmap);
                    FileUtil.saveImg(bitmap, picId);                //保存图片
                    progressDialog.dismiss();
                    //要求更新ImageView
                    mAttacher.update();
                }
            }, 0, 0, ImageView.ScaleType.CENTER_CROP, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    imageView.setBackgroundResource(R.mipmap.picture_defualt);
                    progressDialog.dismiss();
                    Toast.makeText(context, "读取图片时发生错误！" + volleyError.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                }
            });
            mQueue.add(imageRequest);
        }else{
            progressDialog.dismiss();
            Bitmap bitmap = BitmapFactory.decodeFile(Constant.CAMERA_PICTURE_PATH + picId);
            imageView.setImageBitmap(bitmap);
            mAttacher.update();
        }
    }

//  获取头像实例
//    String photo=BuDingMainActivity.mainSharedPreferences.getString("photo","");
//    if(!"".equals(photo)){
//        FileUtil.setupBigImage(photo,mQueue,ivHomeFragmentUserHead);
//    }


    /**
     * 获取文件夹大小
     * @param file File实例
     * @return long
     */
    public static long getFolderSize(File file){

        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++)
            {
                if (fileList[i].isDirectory())
                {
                    size = size + getFolderSize(fileList[i]);

                }else{
                    size = size + fileList[i].length();

                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //return size/1048576;
        return size;
    }

    /**
     * 删除指定目录下文件及目录
     * @param deleteThisPath
     * @param filepath
     * @return
     */
    public static void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {// 处理目录
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {// 如果是文件，删除
                        file.delete();
                    } else {// 目录
                        if (file.listFiles().length == 0) {// 目录下没有文件或者目录，删除
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    /**
     * 格式化单位
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size/1024;
        if(kiloByte < 1) {
            return size + "Byte(s)";
        }

        double megaByte = kiloByte/1024;
        if(megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte/1024;
        if(gigaByte < 1) {
            BigDecimal result2  = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte/1024;
        if(teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }
}
